#!/usr/bin/env perl

use strict;
use warnings FATAL => 'all';
use utf8;

use JSON::PP;

my $data = do { local $/; open my $fh, '<', 'exceptions.json' or die $!; decode_json <$fh> };

my $package = $data->[0];
my $prefix = $data->[1];
my $exns = $data->[2];

for my $type (keys %$exns) {
   for (keys %{ $exns->{$type} }) {
      my @lines = @{ $exns->{$type}{$_} };
      s/^/     * / for @lines;
      $exns->{$type}{$_} = join "\n", @lines;
   }
}

for my $type (keys %$exns) {
   open my $fh, '>', "Tox${prefix}${type}Exception.java"
      or die $!;

   my $codes =
      join ",\n",
      map { "    /**\n$exns->{$type}{$_}\n     */\n    $_" }
      (sort keys %{ $exns->{$type} });

   my $JavaOnly =
   	$codes =~ /\@JavaOnly/
      	? "import im.tox.tox4j.exceptions.JavaOnly;\n"
         : "";

   print $fh <<JAVA;
package im.tox.tox4j.$package.exceptions;

${JavaOnly}import im.tox.tox4j.exceptions.ToxException;
import org.jetbrains.annotations.NotNull;

public final class Tox${prefix}${type}Exception extends ToxException<Tox${prefix}${type}Exception.Code> {

  public enum Code {
$codes,
  }

  public Tox${prefix}${type}Exception(\@NotNull Code code) {
    this(code, "");
  }

  public Tox${prefix}${type}Exception(\@NotNull Code code, String message) {
    super(code, message);
  }

}
JAVA

}
